import time
from pathlib import Path
from threading import Thread

from loguru import logger

from configs.log_conf import log_dir
from src.tools import traverse

dir_list: list[Path] = [Path("dicts")]
flag: bool = True

counter_logger = logger
counter_log_file: Path = Path(log_dir, "counter_{time}.log")

counter_logger.add(
    counter_log_file,
    rotation="100 MB",
    retention="1 week",
    compression="zip",
    format="{time:YYYY-MM-DD at HH:mm:ss} - {level} - {message}",
    filter=lambda x: "[counter]" in x["message"],
    level="INFO",
    enqueue=True,
    encoding="utf-8",
)


def counter() -> None:
    global dir_list, flag

    while flag:
        counter_logger.info("[counter] 目录列表中还剩{}个。".format(len(dir_list)))
        time.sleep(1)

    counter_logger.info("[counter] 运行结束。")


work_logger = logger
work_log_file: Path = Path(log_dir, "work_{time}.log")

work_logger.add(
    work_log_file,
    rotation="100 MB",
    retention="1 week",
    compression="zip",
    format="{time:YYYY-MM-DD at HH:mm:ss} - {level} - {message}",
    filter=lambda x: "[work]" in x["message"],
    level="INFO",
    enqueue=True,
    encoding="utf-8",
)


def work() -> None:
    global dir_list, flag

    try:
        folder: Path = dir_list.pop()
    except IndexError:
        flag = False

    while flag:
        traverse_result: list[Path] = traverse(folder)
        if traverse_result != []:
            dir_list.extend(traverse_result)
            dir_list = list(set(dir_list))

        work_logger.info("[work] {}".format(dir_list))

        try:
            folder = dir_list.pop()
        except IndexError:
            flag = False


def main() -> None:
    count_thread = Thread(target=counter)
    count_thread.start()

    t = Thread(target=work)
    t.start()


if __name__ == "__main__":
    main()
